<template>
  <div>
    <div class="city-search" v-show="visable">
      <input
        type="text"
        placeholder="请输入城市名称"
        @input="getCitiesData"
        v-model="inputValue"
      />
      <div class="city-box" v-if="isInputValueNotEmpty">
        <p @click="searchWeather()" v-if="isInputValueNotEmpty">
          {{ inputCity }}
        </p>
        <p v-if="!isInputValueNotEmpty">似乎没有查找到您要搜索的城市信息</p>
      </div>

      <ul v-show="showList" class="city-list">
        <li v-for="(item, index) in cities" :key="index">
          <div class="interest-cities">
            <div class="city-temp">
              <h2>{{ item.city }}</h2>
            </div>
            <div class="city-edit">
              <button class="edit-btn" @click="handleSelect(item.adcode)">
                查看
              </button>
              <button class="edit-btn" @click="handleDelete(item.adcode)">
                删除
              </button>
            </div>
          </div>
        </li>
      </ul>
      <h2 class="recent text-center text-white" v-if="this.cities == ''">
        暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
      </h2>
      <h2 class="recent text-white">近期天气</h2>
    </div>
    <div class="search-complated" v-show="!visable">
      <p>你正在预览{{ inputCity }}的天气，可以通过右上角的+号按钮保存起来</p>
      <div class="preview-weather">
        <h1>当日气温是：{{ theCityTemp }}&#8451;</h1>
        <h1>当日天气是：{{ theCityWeather }}</h1>
        <h1>当日风向是：{{ theCityWind }}风</h1>
        <h1>当日风力是：{{ theCityPower }}级</h1>
      </div>
      <hr />
    </div>
    <div class="recent-weather">
      <div class="date-weather text-white">
        <ul v-for="(item, index) in weatherinfo" :key="index" class="date">
          <li class="date">
            <span>{{ item.week }}</span>
            <span>{{ item.date | date }}</span>
            <span>{{ item.dayweather }}</span>
            <span>风力{{ item.daypower }}级</span>
          </li>
        </ul>
      </div>

      <!-- Echarts图 -->

      <div class="weather-echarts">
        <chart-block :option="option" class="date-echarts"></chart-block>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import ChartBlock from "@/components/ChartBlock";
import { color } from "echarts";
export default {
  props: {
    iPWeather: Array,
    addInterestCity: Object,
  },
  name: "CitySearch",
  components: {
    ChartBlock,
  },
  filters: {
    // 截取月份和日期
    date(value) {
      return value.slice(5, 10);
    },
  },
  data() {
    return {
      inputValue: "",
      inputCity: "",
      InterestCities: "",
      adcode: "",
      cities: [],
      theCityTemp: "",
      theCityWeather: "",
      theCityWind: "",
      theCityPower: "",
      showList: true, // 下拉列表是否显示
      visable: true,
      weatherinfo: [],
      option: {
        // 设置坐标系
        grid: {
          show: false,
          left: 0,
          right: 0,
          top: 10,
          bottom: 0,
        },
        xAxis: {
          data: [],
        },
        yAxis: { show: false },
        series: [
          {
            data: [],
            type: "line",
            smooth: true, //平滑效果
            label: {
              show: true,
              position: "top",
              color: "#fff",
              formatter: function (params) {
                return "白" + params.value + "℃";
              },
            },
          },
          {
            data: [],
            type: "line",
            smooth: true,//平滑效果
            label: {
              show: true,
              position: "bottom", //设置标签位置
              color: "#fff", //设置标签字体颜色
              formatter: function (params) {
                return "晚" + params.value + "℃";
              },
            },
          },
        ],
      },
    };
  },
  mounted() {
    this.start();
  },
  methods: {
    start() {
      this.cities = JSON.parse(localStorage.getItem("myCity"));
    },
    handleSelect(e) {
      this.adcode = e;
      this.searchWeather();
    },
    handleDelete(e) {
      // 获取LocalStorage中存储的数组
      let myCity = JSON.parse(localStorage.getItem("myCity"));
      console.log(myCity);
      // 找到要删除的元素索引
      myCity = myCity.filter((item) => item.adcode !== e);
      console.log(myCity);
      // 将修改后的数组重新存储到LocalStorage
      localStorage.setItem("myCity", JSON.stringify(myCity));
      location.reload();
    },
    async getCitiesData(e) {
      try {
        const cityTip = await axios.get(
          `http://restapi.amap.com/v3/geocode/geo?&address=${e.target.value}&key=ce4e514377b2ec6820b7e123de8b8008`
        );
        this.adcode = cityTip.data.geocodes[0].adcode;
        this.inputCity = cityTip.data.geocodes[0].city;
        this.InterestCities = cityTip.data.geocodes[0];
      } catch {
        (error) => {
          console.error("获取城市数据时发生错误：", error);
        };
      }
    },
    async searchWeather() {
      try {
        const weatherData = await axios.get(
          `https://restapi.amap.com/v3/weather/weatherInfo?city=${this.adcode}&key=ce4e514377b2ec6820b7e123de8b8008&extensions=all`
        );
        this.weatherinfo = weatherData.data.forecasts[0].casts;
        this.theCityTemp = weatherData.data.forecasts[0].casts[0].daytemp;
        this.theCityWeather = weatherData.data.forecasts[0].casts[0].dayweather;
        this.theCityWind = weatherData.data.forecasts[0].casts[0].daywind;
        this.theCityPower = weatherData.data.forecasts[0].casts[0].daypower;
        console.log(this.weatherinfo);
        for (let i = 0; i < this.weatherinfo.length; i++) {
          if (i == 0) {
            this.weatherinfo[i].week = "今天";
          } else if (i == 1) {
            this.weatherinfo[i].week = "明天";
          } else {
            switch (this.weatherinfo[i].week) {
              case "1":
                this.weatherinfo[i].week = "星期一";
                break;
              case "2":
                this.weatherinfo[i].week = "星期二";
                break;
              case "3":
                this.weatherinfo[i].week = "星期三";
                break;
              case "4":
                this.weatherinfo[i].week = "星期四";
                break;
              case "5":
                this.weatherinfo[i].week = "星期五";
                break;
              case "6":
                this.weatherinfo[i].week = "星期六";
                break;
              case "7":
                this.weatherinfo[i].week = "星期日";
              default:
                break;
            }
          }
        }
        this.option.series[0].data = this.weatherinfo.map((obj) => obj.daytemp);
        this.option.series[1].data = this.weatherinfo.map(
          (obj) => obj.nighttemp
        );
        console.log(this.visable)
        this.visable = !this.visable;
      } catch (error) {
        // 捕获错误
        console.error(error);
      }
    },
  },
  computed: {
    isInputValueNotEmpty() {
      return this.inputValue.trim() !== "";
    },
  },
  watch: {
    iPWeather(newValue) {
      this.weatherinfo = newValue;
      for (let i = 0; i < this.weatherinfo.length; i++) {
        if (i == 0) {
          this.weatherinfo[i].week = "今天";
        } else if (i == 1) {
          this.weatherinfo[i].week = "明天";
        } else {
          switch (this.weatherinfo[i].week) {
            case "1":
              this.weatherinfo[i].week = "星期一";
              break;
            case "2":
              this.weatherinfo[i].week = "星期二";
              break;
            case "3":
              this.weatherinfo[i].week = "星期三";
              break;
            case "4":
              this.weatherinfo[i].week = "星期四";
              break;
            case "5":
              this.weatherinfo[i].week = "星期五";
              break;
            case "6":
              this.weatherinfo[i].week = "星期六";
              break;
            case "7":
              this.weatherinfo[i].week = "星期日";
            default:
              break;
          }
        }
      }
      this.option.series[0].data = this.weatherinfo.map((obj) => obj.daytemp);
      this.option.series[1].data = this.weatherinfo.map((obj) => obj.nighttemp);
    },
  },
};
</script>

<style scoped>
.city-list {
  margin-top: 2rem;
}
.city-search {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-bottom: 2rem;
  padding-top: 1rem;
}
.city-search input {
  width: 100%;
  height: 40px;
  border: none;
  outline: none;
  border-bottom: 1px solid white;
  background-color: var(--tw-bg-opacity);
}
.recent {
  margin-top: 2rem;
}
.interest-cities {
  display: flex;
  align-items: center;
}
.interest-cities:hover .city-edit {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.city-temp {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 40px;
  padding: 0.5rem 1rem;
  margin: 0.5rem 0;
  color: white;
  background-color: #004e71;

  width: 100%;
}
.city-box {
  width: 100%;
  height: 40px;
  padding: 0.5rem 1rem;
  color: white;
  background-color: #004e71;
}
.city-edit {
  display: none;
  width: 20%;
  height: 40px;
}
.edit-btn {
  border: none;
  width: 80px;
  height: 40px;
  margin-left: 0.5rem;
  color: #fff;
  background-color: #eab308;
}
.search-complated p {
  width: 100%;
  height: 40px;
  font-size: 1rem;
  text-align: center;
  line-height: 40px;
  background-color: #004e71;
  color: #fff;
}
.preview-weather {
  margin: 1rem 0;
  text-align: center;
}
.preview-weather h1 {
  margin: 1.5rem 0;
  color: #fff;
}
.recent-weather {
  margin-top: 0.5rem;
  padding: 2.5rem 3rem 0 3rem;
  border-radius: 0.25rem;
  background-color: #004e71;
}
.date-weather {
  display: flex;
  gap: 1.5rem;
  height: 144px;
}
.date {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.date span {
  flex: 1;
  height: 24px;
}
/* 天气图 */
.weather-echarts {
  display: flex;
  align-items: center;
  margin-top: 2.5rem;
  width: 100%;
  height: 200px;
}
.date-echarts {
  width: 100%;
}
/* 列表 */
</style>